import { BadGatewayException, Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { User } from 'src/decorator/user.decorator';
import { BaoMinModel } from 'src/mongodb/models/baominModel/BaoMinModel';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { UserModel } from 'src/mongodb/models/userModel/User.models';
import { deleteUserDto, updateUserDto } from '../userApi/userDto/userDto';
import { getUserListDto, searchAppUserDto } from './appUserDto/appUserDto';

@Controller('web')
@UseGuards(AuthGuard("jwtweb"))
export class AppUserController {

    constructor(
        @InjectModel(UserModel) private readonly appuser: ModelType<UserModel>,
        @InjectModel(BaoMinModel) private readonly baoMin: ModelType<BaoMinModel>,
        @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
    ) { }

    /**
    * @Description: 查询用户列表
    * @param pageNo {Number} 页码
    * @param pageSize {Number}  每页条数
    * @return: Promise
    */
    @Get('getAppUserList')
    async getAppUserList(@Query() query: getUserListDto, @User() user) {
        try {
            if (user.name == 'admin') {
                let data: { pageNo: number | string, pageSize: number | string } = query
                if (typeof data.pageNo == 'string') {
                    data.pageNo = parseInt(data.pageNo)
                }
                if (typeof data.pageSize == 'string') {
                    data.pageSize = parseInt(data.pageSize)
                }

                const total = await this.appuser.countDocuments()
                const userlist = await this.appuser.find().skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ '_id': -1 });
                return { total, data: userlist }
            } else {
                const res = await this.qudaobao.find({ userid: user._id }, 'mark')
                const resarr = []
                res.forEach(element => {
                    resarr.push(element.mark)
                });
                let data: { pageNo: number | string, pageSize: number | string } = query
                if (typeof data.pageNo == 'string') {
                    data.pageNo = parseInt(data.pageNo)
                }
                if (typeof data.pageSize == 'string') {
                    data.pageSize = parseInt(data.pageSize)
                }

                const total = await this.appuser.countDocuments({ mark: { $in: resarr } })
                const userlist = await this.appuser.find({ mark: { $in: resarr } }).skip((data.pageNo - 1) * data.pageSize).limit(data.pageSize).sort({ '_id': -1 });
                return { total, data: userlist }

            }


        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 搜索用户
    * @param name {Number} 账户
    * @return: Promise
    */
    @Get('searchAppUser')
    async searchAppUser(@Query() query: searchAppUserDto) {
        try {
            const userlist = await this.appuser.find({ name: query.name })
            return { total: userlist.length, data: userlist }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 删除用户
    * @param id {String} 用户id
    * @return: Promise
    */
    @Post('deleteAppUser')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteAppUser(@Body() body: deleteUserDto) {
        try {
            await this.appuser.deleteOne({ _id: body.id })
            this.baoMin.deleteOne({ userid: body.id }).then()
            return { code: 200, message: '删除成功' }

        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



    /**
    * @Description: 删除全部用户
    * @return: Promise
    */
    @Post('deleteAppUserAll')
    @UseGuards(AuthGuard("jwtweb"))
    async deleteAppUserAll() {
        try {
            await this.appuser.deleteMany({})
            this.baoMin.deleteMany({}).then()
            return { code: 200, message: '删除成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }


    /**
    * @Description: 修改用户状态
    * @param id {String} 用户id
    * @param status {Boolean} 状态
    * @return: Promise
    */
    @Post('updateUser')
    @UseGuards(AuthGuard("jwtweb"))
    async updateUser(@Body() body: updateUserDto) {
        try {
            await this.appuser.updateOne({ _id: body.id }, { status: body.status })
            return { code: 200, message: '修改成功' }
        } catch (error) {
            throw new BadGatewayException(error)
        }
    }



}
